# coding:utf-8
from turtle import update
from PyQt6.QtCore import Qt, QUrl
from PyQt6.QtWidgets import QHBoxLayout, QWidget, QFrame, QHBoxLayout, QTableWidgetItem, QPushButton, QFormLayout, QSpacerItem, QSizePolicy
from qfluentwidgets import PushButton, TableWidget, MessageBoxBase, SubtitleLabel, LineEdit, SpinBox, SearchLineEdit, ComboBox, Slider

from .base_gallery_view import GalleryInterface
from .common.translator import Translator
from .common.style_sheet import StyleSheet
from .common.signal_bus import signalBus
from dto.stock_status_enum import StockStatuEnum
from dto.stock_info_monitor import AntMonitorStockInfo

from service.stock_service import getAllStockList, saveMonitorStock, deleteOneStock, getByStockCode, updateMonitorStock


class AllStockListInterface(GalleryInterface):
    def __init__(self, parent=None):
        t = Translator()
        super().__init__(
            title=t.view,
            subtitle="qfluentwidgets.components.widgets",
            parent=parent
        )
        self.setObjectName('viewInterface')

        # 添加顶部搜索框
        self.topView = TopWidgetView(self)
        self.vBoxLayout.addWidget(self.topView)

        # 添加中间列表
        self.stockChat = TableFrame(self)
        self.vBoxLayout.addWidget(self.stockChat)


class SelfSearchLineEdit(SearchLineEdit):
    """ Search line edit """

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setPlaceholderText(self.tr('通过股票代码/名称查询'))
        self.setFixedWidth(304)
        self.textChanged.connect(self.search)


class TopWidgetView(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent=parent)

        # 顶部搜索框
        self.searchLineEdit = SelfSearchLineEdit(self)

        # 新增新股
        self.addButton = PushButton(self.tr('新增新股'))
        self.addButton.setFixedWidth(120)
        self.addButton.clicked.connect(self.showCustomDialog)

        #
        self.updateButton = PushButton(self.tr('刷新所有'))
        self.updateButton.setFixedWidth(120)

        self.spacer = QSpacerItem(20, 10, QSizePolicy.Policy.Fixed, QSizePolicy.Policy.Minimum)

        self.hBoxLayout = QHBoxLayout()

        self.__initWidget()

    def __initWidget(self):

        self.hBoxLayout.setSpacing(0)
        self.hBoxLayout.setContentsMargins(0, 0, 0, 0)
        self.hBoxLayout.addWidget(self.searchLineEdit)
        self.hBoxLayout.addStretch(1)
        self.hBoxLayout.addWidget(self.addButton)

        self.hBoxLayout.addItem(self.spacer)
        self.hBoxLayout.addWidget(self.updateButton)

        self.searchLineEdit.clearSignal.connect(self.showAllIcons)
        self.searchLineEdit.searchSignal.connect(self.search)

        self.setLayout(self.hBoxLayout)

    def search(self, keyWord: str):
        print("查询所有股票")

    def showAllIcons(self):
        print("清空查询")

    def showCustomDialog(self):
        w = CustomMessageBox(self.window(), self)
        w.exec()


class Frame(QFrame):

    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.hBoxLayout = QHBoxLayout(self)
        self.hBoxLayout.setContentsMargins(0, 8, 0, 0)

        self.setObjectName('frame')
        StyleSheet.VIEW_INTERFACE.apply(self)

    def addWidget(self, widget):
        self.hBoxLayout.addWidget(widget)


class TableFrame(TableWidget):

    def __init__(self, parent=None):
        super().__init__(parent)

        self.verticalHeader().hide()
        self.setBorderRadius(8)
        self.setBorderVisible(True)

        self.setColumnCount(16)
        self.setRowCount(100)
        self.setHorizontalHeaderLabels([
            "股票名称", "股票代码", "关注等级", "风险等级", "当前持股数",
            "最大持股数", "原始价格", "当前价格", "盈利比例", "盈利金额",
            "目标比例", "止损比例", "股票状态", "打标标签", "后续建议",
            "上涨天数", "操作方式"
        ])

        self.refreshData()

        signalBus.dataSignal.connect(self.outRefreshData)

    def outRefreshData(self, type, data):
        self.refreshData()

    def refreshData(self):
        self.clearContents()
        self.stockList = getAllStockList()

        # 填充数据
        for row, stock in enumerate(self.stockList):
            self.setItem(row, 0, QTableWidgetItem(stock.stock_name))
            self.setItem(row, 1, QTableWidgetItem(stock.stock_code))
            self.setItem(row, 2, QTableWidgetItem(str(stock.stock_focus_level or '')))
            self.setItem(row, 3, QTableWidgetItem(str(stock.stock_risk_level or '')))
            self.setItem(row, 4, QTableWidgetItem(str(stock.stock_current_number or '')))
            self.setItem(row, 5, QTableWidgetItem(str(stock.stock_max_number or '')))
            self.setItem(row, 6, QTableWidgetItem(str(stock.monitor_origin_price or '')))
            self.setItem(row, 7, QTableWidgetItem(str(stock.monitor_current_price or '')))
            self.setItem(row, 8, QTableWidgetItem(str(stock.monitor_income_ratio or '')))
            self.setItem(row, 9, QTableWidgetItem(str(stock.monitor_income_money or '')))
            self.setItem(row, 10, QTableWidgetItem(str(stock.monitor_target_ratio or '')))
            self.setItem(row, 11, QTableWidgetItem(str(stock.monitor_stop_ratio or '')))
            self.setItem(row, 12, QTableWidgetItem(str(stock.stock_status or '')))
            self.setItem(row, 13, QTableWidgetItem(stock.stock_tag or ''))
            self.setItem(row, 14, QTableWidgetItem(stock.stock_next_advice or ''))
            self.setCellWidget(
                row, 15, self.create_buttons_widget(stock.stock_code))

        self.resizeColumnsToContents()

    def create_buttons_widget(self, stock_code):
        # 创建一个小部件用于容纳按钮
        widget = QWidget()

        # 创建布局
        layout = QHBoxLayout()

        # 创建第一个按钮
        btn1 = QPushButton("更新")
        btn1.clicked.connect(lambda: self.on_button_click(
            "Edit", stock_code))
        layout.addWidget(btn1)

        # 创建第二个按钮
        btn2 = QPushButton("删除")
        btn2.clicked.connect(lambda: self.on_button_click(
            "Delete", stock_code))
        layout.addWidget(btn2)

        # 创建第二个按钮
        btn3 = QPushButton("详情")
        btn3.clicked.connect(lambda: self.on_button_click(
            "Detail", stock_code))
        layout.addWidget(btn3)

        # 将布局应用到小部件
        widget.setLayout(layout)
        return widget

    def on_button_click(self, action, row):
        if action == "Edit":
            print(f"Edit button clicked on row {row}")
            self.updateStock(row)
        elif action == "Delete":
            self.deleteOneStock(row)
        elif action == "Detail":
            print(f"查询详情 {row}")
            signalBus.switchToSampleCard.emit("StockDayView", 0, row)

    def deleteOneStock(self, stockCode):
        deleteOneStock(stockCode)
        signalBus.dataSignal.emit("refreshStockList", "")

    def updateStock(self, stockCode):
        w = CustomMessageBox(self.window(), self)
        stockInfo = getByStockCode(stockCode)
        w.updateStock(stockInfo)
        w.exec()


class CustomMessageBox(MessageBoxBase):
    """ Custom message box """

    def __init__(self, parent=None, outView=None):
        super().__init__(parent)

        self.outView = outView

        self.isUpate = False

        # 添加标题栏
        self.titleLabel = SubtitleLabel(self.tr('添加新股'), self)
        self.viewLayout.addWidget(self.titleLabel)
        self.formLayout = QFormLayout()
        self.formLayout.setVerticalSpacing(10)

        # 录入股票代码
        self.codeEdit = LineEdit(self)
        self.codeEdit.setPlaceholderText(self.tr('请填写股票代码'))
        self.codeEdit.setText("002670.SZ")
        self.codeEdit.setClearButtonEnabled(True)
        self.formLayout.addRow("股票代码:", self.codeEdit)

        # 录入股票关注等级
        self.focusLevelEdit = Slider(Qt.Orientation.Horizontal)
        self.focusLevelEdit.setValue(3)
        self.focusLevelEdit.setRange(1, 10)  # 假设关注等级范围为 1 到 10
        self.focusLevelEdit.setTickInterval(1)
        self.focusLevelEdit.setSingleStep(1)
        self.formLayout.addRow("股票关注等级(1):", self.focusLevelEdit)

        # 录入股票风险等级
        self.riskLevelEdit = Slider(Qt.Orientation.Horizontal)
        self.riskLevelEdit.setValue(1)
        self.riskLevelEdit.setTickInterval(1)
        self.riskLevelEdit.setSingleStep(1)
        self.riskLevelEdit.setRange(1, 5)  # 假设风险等级范围为 1 到 5
        self.formLayout.addRow("股票风险等级:", self.riskLevelEdit)

        # 录入股票当前持股数
        self.currentNumberEdit = LineEdit(self)
        self.currentNumberEdit.setPlaceholderText(self.tr('请填写当前持股数'))
        self.currentNumberEdit.setClearButtonEnabled(True)
        self.formLayout.addRow("股票当前持股数:", self.currentNumberEdit)

        # 录入最大持股数
        self.maxNumberEdit = LineEdit(self)
        self.maxNumberEdit.setPlaceholderText(self.tr('请填写最大持股数'))
        self.maxNumberEdit.setClearButtonEnabled(True)
        self.formLayout.addRow("最大持股数:", self.maxNumberEdit)

        # 录入原始价格
        self.originPriceEdit = LineEdit(self)
        self.originPriceEdit.setClearButtonEnabled(True)
        self.originPriceEdit.setClearButtonEnabled(True)
        self.formLayout.addRow("原始价格:", self.originPriceEdit)

        # 录入当前价格
        self.currentPriceEdit = LineEdit(self)
        self.currentPriceEdit.setClearButtonEnabled(True)
        self.currentPriceEdit.setClearButtonEnabled(True)
        self.formLayout.addRow("当前价格:", self.currentPriceEdit)

        # 录入盈利比例
        self.incomeRatioEdit = Slider(Qt.Orientation.Horizontal)
        self.incomeRatioEdit.setRange(1, 50)  # 假设关注等级范围为 1 到 10
        self.incomeRatioEdit.setValue(15)
        self.incomeRatioEdit.setTickInterval(1)
        self.incomeRatioEdit.setSingleStep(1)
        self.formLayout.addRow("盈利比例:", self.incomeRatioEdit)

        self.incomeMoneyEdit = Slider(Qt.Orientation.Horizontal)
        self.incomeMoneyEdit.setRange(1, 50)  # 假设关注等级范围为 1 到 10
        self.incomeMoneyEdit.setValue(15)
        self.incomeMoneyEdit.setTickInterval(1)
        self.incomeMoneyEdit.setSingleStep(1)
        self.formLayout.addRow("盈利金额:", self.incomeMoneyEdit)

        # 录入目标比例
        self.targetRatioEdit = Slider(Qt.Orientation.Horizontal)
        self.targetRatioEdit.setRange(1, 50)  # 假设关注等级范围为 1 到 10
        self.targetRatioEdit.setValue(15)
        self.targetRatioEdit.setTickInterval(1)
        self.targetRatioEdit.setSingleStep(1)
        self.formLayout.addRow("目标比例:", self.targetRatioEdit)

        # 录入止损比例
        self.stopRatioEdit = Slider(Qt.Orientation.Horizontal)
        self.stopRatioEdit.setRange(1, 20)  # 假设关注等级范围为 1 到 10
        self.targetRatioEdit.setValue(10)
        self.stopRatioEdit.setTickInterval(1)
        self.stopRatioEdit.setSingleStep(1)
        self.formLayout.addRow("止损比例:", self.stopRatioEdit)

        # 录入股票状态
        self.statusComboBox = ComboBox(self)
        self.statusComboBox.addItems(StockStatuEnum.get_status_list())  # 从静态值获取状态
        self.formLayout.addRow("选择股票状态:", self.statusComboBox)

        # 录入打标标签
        self.tagEdit = LineEdit(self)
        self.tagEdit.setPlaceholderText(self.tr('请填写打标标签'))
        self.formLayout.addRow("打标标签:", self.tagEdit)

        # 录入打标标签
        self.ohterEdit = LineEdit(self)
        self.ohterEdit.setPlaceholderText(self.tr('请填写备注'))
        self.formLayout.addRow("备注信息:", self.ohterEdit)

        self.viewLayout.addLayout(self.formLayout)

        # 提交
        self.yesButton.setText(self.tr('提交'))
        self.widget.setMinimumWidth(360)
        self.yesButton.setDisabled(False)
        self.yesButton.clicked.connect(self.submitForm)

    def _validateUrl(self):
        if self.codeEdit.text and self.priceEdit.text and self.ratioEdit.text:
            self.yesButton.setEnabled(True)

    def submitForm(self):
        stock_info = AntMonitorStockInfo(
            stock_code=self.codeEdit.text(),
            stock_focus_level=int(self.focusLevelEdit.value() or 0),
            stock_risk_level=int(self.riskLevelEdit.value() or 0),
            stock_current_number=int(self.currentNumberEdit.text() or 0),
            stock_max_number=int(self.maxNumberEdit.text() or 0),
            monitor_origin_price=float(self.originPriceEdit.text() or 0),
            monitor_current_price=float(self.currentPriceEdit.text() or 0),
            monitor_income_ratio=float(self.incomeRatioEdit.value() or 0),
            monitor_income_money=float(self.incomeMoneyEdit.value() or 0),
            monitor_target_ratio=float(self.targetRatioEdit.value() or 0),
            monitor_stop_ratio=float(self.stopRatioEdit.value() or 0),
            stock_status=self.statusComboBox.currentText(),
            stock_tag=self.tagEdit.text(),
            other_info=self.ohterEdit.text(),
            is_update=self.isUpate
        )
        if (self.isUpate):
            updateMonitorStock(stock_info)
        else:
            saveMonitorStock(stock_info)
        signalBus.dataSignal.emit("refreshStockList", "")

    def updateStock(self, stock_data: AntMonitorStockInfo):
        self.codeEdit.setText(stock_data.stock_code)
        self.focusLevelEdit.setValue(stock_data.stock_focus_level or 1)  # 如果可能为 None，可以提供默认值
        self.riskLevelEdit.setValue(stock_data.stock_risk_level or 1)
        self.currentNumberEdit.setText(str(stock_data.stock_current_number or ''))
        self.maxNumberEdit.setText(str(stock_data.stock_max_number or ''))
        self.originPriceEdit.setText(str(stock_data.monitor_origin_price or ''))
        self.currentPriceEdit.setText(str(stock_data.monitor_current_price or ''))
        self.incomeRatioEdit.setValue(int(stock_data.monitor_income_ratio or 0))
        self.incomeMoneyEdit.setValue(int(stock_data.monitor_income_money or 0))
        self.targetRatioEdit.setValue(int(stock_data.monitor_target_ratio or 0))
        self.stopRatioEdit.setValue(int(stock_data.monitor_stop_ratio or 0))
        self.statusComboBox.setCurrentText(stock_data.stock_status or '')
        self.tagEdit.setText(stock_data.stock_tag or '')
        self.ohterEdit.setText(stock_data.other_info or '')
        self.isUpate = True


def calculate_target_profit(monitor_origin_price, stock_current_number, monitor_income_ratio):
    # 计算目标盈利金额
    monitor_income_money = monitor_origin_price * stock_current_number * (monitor_income_ratio / 100)
    return monitor_income_money
